<?php

require_once( dirname(__FILE__) . DIRECTORY_SEPARATOR . "bootstrap.php");
require_once("OAuth/SimpleRequest.php");

if ( is_file( dirname(__FILE__) . DIRECTORY_SEPARATOR . "localDefines.php"))
	require_once( dirname(__FILE__) . DIRECTORY_SEPARATOR . "localDefines.php");

/**************** CONFIGURATION ****************/
/**
 * This set of information will be provided to you by Evernote when
 * you register for use of the API.
 *
 */
define("consumerKey", "en-oauth-test");
define("consumerSecret", "0123456789abcdef");
define("spHostname","https://stage.evernote.com");
define("requestTokenUrl", spHostname . "/oauth");
define("accessTokenUrl", spHostname . "/oauth");
define("authorizationUrlBase", spHostname . "/OAuth.action");
define("noteStoreHost", "stage.evernote.com");
define("noteStorePort", "80");
define("noteStoreProto", "https");
define("noteStoreUrl", "edam/note/");

/**
 * Handlers for redirect schema.
 * Evernote provides two redirect schemas - FULL page redirects and 
 * EMBEDed page redirects - as far as the user sees - are not redirects at all,
 * because they are to be embeded on the Consumer's page.
 *
 * Redirects occur when Consumer needs to redirect the User to Evernote in order to
 * authorize Request Token recieved from Evernote by the Consumer.
 *
 */
define("REDIR_FULL", "FULL");
define("REDIR_EMBED", "EMBED");

/**
 * Callback configuration:
 *  $callbackUrl is the URL to which Evernote should redirect user after that user authorized Request Token
 *  $callbackEmebedUrl is the same as $callbackUrl but for EMEBEDed redirect schema
 *
 */
define("callbackUrl", "index.php");
define("callbackEmbedUrl", "callback.php");



/**************** INIT ****************/
// start session if none exists - we use it to track tokens and what not
session_start();

// update ourselves with redirect schema preference
$redirSchema = (isset($_GET['redirSchema'])) ? $_GET['redirSchema'] : null;
if (is_null($redirSchema))
	$redirSchema = (isset($_SESSION['redirSchema']) && $_SESSION['redirSchema'] == REDIR_EMBED) ? REDIR_EMBED : REDIR_FULL;
$_SESSION['redirSchema'] = $redirSchema;

if (isset($_GET['oauth_token']))
	$_SESSION['requestToken'] = $_GET['oauth_token'];

// intercept action
$action = isset($_GET['action']) ? $_GET['action'] : null;

// callback URL - this is passed to Evernote so that Evernote can return to this URL
// after the user authorizes the request token
$authorizationUrl = null;

/**************** ACTIONS ****************/
/**
 * Reset state
 *
 */
function resetState() {
	resetSession();
	$redirSchema = REDIR_FULL;
	print "Removed all attributes from user session\n";
}
/**
 * Retrieves request token from Evernote
 *
 */
function getRequestToken() {
	// Send an OAuth message to the Provider asking for a new Request
	// Token because we don't have access to the current user's account.
	$oauthRequestor = new OAuth_SimpleRequest(requestTokenUrl, consumerKey, consumerSecret);
	print "Request: " . $oauthRequestor->encode() . "\n";
	try {
		$oauthRequestor->sendRequest();
		print "Reply: " . $oauthRequestor->getResponseBody() . "\n";
		$r = $oauthRequestor->getResponseStruct();
		$reply = $oauthRequestor->getResponseStruct();
		if (isset($reply['oauth_token'])) {
			$_SESSION['requestToken'] = $reply['oauth_token'];
		}
	} catch (HTTP_Exception $e) {
		print $e->getMessage() . ": " . $e->getCode() . " " . $e->getCauseMessage() . "\n";
	}
}
/**
 * Retrieves access token from Evernote
 *
 */
function getAccessToken() {
	// Send an OAuth message to the Provider asking to exchange the
	// existing Request Token for an Access Token
	$oauthRequestor = new OAuth_SimpleRequest(requestTokenUrl, consumerKey, consumerSecret);
	$oauthRequestor->setParameter("oauth_token", $_SESSION['requestToken']);
	print "Request: " . $oauthRequestor->encode() . "\n";
	
	try {
		$oauthRequestor->sendRequest();
		print "Reply: " . $oauthRequestor->getResponseBody() . "\n";
		$reply = $oauthRequestor->getResponseStruct();
		if (isset($reply['oauth_token']))
			$_SESSION['accessToken'] = $reply['oauth_token'];
		if (isset($reply['edam_shard']))
			$_SESSION['shardId'] = $reply['edam_shard'];
		if (isset($_SESSION['requestToken']))
			unset($_SESSION['requestToken']);

	} catch (HTTP_Exception $e) {
		print $e->getMessage() . ": " . $e->getCode() . " " . $e->getCauseMessage() . "\n";
	}
}
/**
 * Handles callback after user has authorized request token
 *
 */
function callbackReturn() {
	if (isset($_GET['requestToken']))
		$_SESSION['requestToken'] = $_GET['requestToken'];
}
/**
 * Lists user's notebooks. This is a sample interaction with Evernote service
 *
 */
function listNotebooks() {
	if (!isset($_SESSION['shardId'])) print "No shardId. ";
	if (!isset($_SESSION['accessToken'])) print "No accessToken. ";
	if (!isset($_SESSION['accessToken']) || !isset($_SESSION['shardId'])) 
		return;
	
	try {
		$noteStoreTrans = new THttpClient(noteStoreHost, noteStorePort, noteStoreUrl . $_SESSION['shardId'], noteStoreProto);
		$noteStoreProt = new TBinaryProtocol($noteStoreTrans);
		$noteStore = new NoteStoreClient($noteStoreProt, $noteStoreProt);
		$notebooks = $noteStore->listNotebooks($_SESSION['accessToken']);
		if (!empty($notebooks)) {
			foreach ($notebooks as $notebook) {
				print "Notebook: ".$notebook->name."\n";
			}
		}
	} catch (edam_error_EDAMSystemException $e) {
		if (isset(edam_error_EDAMErrorCode::$__names[$e->errorCode])) {
			print edam_error_EDAMErrorCode::$__names[$e->errorCode] . ": " . $e->parameter . "\n";
		} else {
			print $e->getCode() . ": " . $e->getMessage() . "\n";
		}
	} catch (edam_error_EDAMUserException $e) {
		if (isset(edam_error_EDAMErrorCode::$__names[$e->errorCode])) {
			print edam_error_EDAMErrorCode::$__names[$e->errorCode] . ": " . $e->parameter . "\n";
		} else {
			print $e->getCode() . ": " . $e->getMessage() . "\n";
		}
	} catch (edam_error_EDAMNotFoundException $e) {
		if (isset(edam_error_EDAMErrorCode::$__names[$e->errorCode])) {
			print edam_error_EDAMErrorCode::$__names[$e->errorCode] . ": " . $e->parameter . "\n";
		} else {
			print $e->getCode() . ": " . $e->getMessage() . "\n";
		}
	} catch (Exception $e) {
		print $e->getMessage();
	}
}

/**************** OTHER FUNCTIONS ****************/
/**
 * Constructs and returns callback url relevant for current redirect schema
 */
function getCallbackUrl() {
	global $redirSchema;
	global $authorizationUrl;
	
	if (empty($authorizationUrl)) {
		$cbUrl = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'];
		$cbUrl = preg_replace("/[^\/]+$/", "", $cbUrl);
		if (!empty($redirSchema) && $redirSchema == REDIR_EMBED)
			$cbUrl .= callbackEmbedUrl;
		else
			$cbUrl .= callbackUrl;
			
		$authorizationUrl = authorizationUrlBase . "?oauth_callback=" .
			rawurlencode($cbUrl) . "&oauth_token=" .
			$_SESSION['requestToken'];
		if (!empty($redirSchema) && $redirSchema == REDIR_EMBED)
			$authorizationUrl .= "&format=microclip";
	}
	return $authorizationUrl;
}

function resetSession() {
	$_SESSION = array();
	$_SESSION['requestToken'] = null;
	$_SESSION['accessToken'] = null;
}


/**************** MAIN ****************/
if (isset($action) && !empty($action)) { ?>
    <hr/>
    <h3>Action results:</h3>
    <pre>
<?php 
	switch($action) {
		case "reset":
			resetState();
			break;
		case "getRequestToken":
			getRequestToken();
			break;
		case "getAccessToken":
			getAccessToken();
			break;
		case "callbackReturn":
			callbackReturn();
			break;
		case "listNotebooks":
			listNotebooks();
			break;
	}
?>
	</pre>
    <hr/>
<?php
}?>

<!-- Redirection method selection -->
<form>
    Redirect method: <select action="/EDAMWebTest" 
        method="GET" 
        name="redirSchema"
        onChange="document.forms[0].submit();">
        <option value="<?= REDIR_FULL ?>" <?php if (isset($redirSchema) && 
        	$redirSchema == REDIR_FULL) echo "selected" ?> >Full page</option>
        <option value="<?= REDIR_EMBED ?>" <?php if (isset($redirSchema) &&
        	$redirSchema == REDIR_EMBED) echo "selected" ?> >Embeded authorization</option>
    </select>
</form>

<!-- Information used by consumer -->
<h3>Evernote EDAM API Web Test State</h3>
Consumer key: <?= consumerKey ?><br/>
Request token URL: <?= requestTokenUrl ?><br/>
Access token URL: <?= accessTokenUrl ?><br/>
Authorization URL Base: <?= authorizationUrlBase ?><br/>
<br/>
User request token: <?= $_SESSION['requestToken'] ?><br/>
User access token: <?= $_SESSION['accessToken'] ?><br/>
User shardId: <?= $_SESSION['shardId'] ?>

<!-- Manual operation controls -->
<hr/>
<h3>Actions</h3>

<!-- Reset state -->
<a href="?action=reset">Reset user session</a><br/>


<?php if (empty($_SESSION['accessToken']) && empty($_SESSION['requestToken'])): ?>
	<!-- Request Request Token -->
	<a href='?action=getRequestToken'>Get OAuth Request Token from Provider</a><br/>
<?php endif; ?>

<?php 
// AUTH_LINKS
if (empty($_SESSION['accessToken']) && !empty($_SESSION['requestToken'])) { ?>
	<!-- Link to request access token from service provider -->
	<a href="?action=getAccessToken">
	  Get OAuth Access Token from Provider
	</a>
	<br/>

	<!-- Link to obtain user authorization -->
<?php if (!empty($redirSchema) && $redirSchema == REDIR_EMBED) { ?>
    <a href='<?= getCallbackUrl() ?>' target='iframe1'>Send user to get authorization</a><br/>
    <iframe name="iframe1" src="about:blank" frameborder="1" scrolling='no'
            width="400" height="200"></iframe>
<?php } else { ?>
    <a href='<?= getCallbackUrl() ?>'>Send user to get authorization</a>
<?php } ?>
    <br/>

<?php
// END OF AUTH_LINKS
} ?>

<?php if (!empty($_SESSION['accessToken'])): ?>
  <!-- Sample usage -->
  <a href="?action=listNotebooks">List notebooks in account</a><br/>
<?php endif; ?>
